package com.facesteel.speech_play.utils;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.facesteel.speech_play.SpeechPlayHelper;

import io.flutter.plugin.common.MethodChannel.Result;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SpeechPlayer {

    private static MediaPlayer mediaPlayer;

    private static String savedFilePath;

    // 新增：播放状态标记
    private static boolean isPrepared = false;

    private static int _duration = 0;

    // 蓝牙音频路由工具
    private static BluetoothAudioRouter bluetoothRouter;

    public static void startSpeech(Context context, String filePath,
                                   int startTime,
                                   int duration,
                                   Result result){
        stopSpeech(); // 先停止之前的铃声
        try {

            savedFilePath = filePath;

            // 初始化蓝牙路由器
            initBluetoothRouter(context);

            mediaPlayer = new MediaPlayer();

//            mediaPlayer.setDataSource(context, Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.custom_dial_tone));

            mediaPlayer.setDataSource(filePath);

            // 关键配置：绑定通话音量通道
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
            mediaPlayer.setAudioAttributes(
                    new AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) // 通信用途标识
                            .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)   // 语音内容类型
                            .build()
            );

            mediaPlayer.setLooping(false);

            // 播放完成监听
            mediaPlayer.setOnCompletionListener(mp -> {
                stopSpeech();
                Log.d("MediaPlayer", "播放自然结束");
                SpeechPlayHelper.getInstance().onListenerCompleted();
            });

//            mediaPlayer.prepare();
//            mediaPlayer.start();

            // 异步准备（更适合大文件或网络流）
            mediaPlayer.setOnPreparedListener(mp -> {
                isPrepared = true;

                // 如果蓝牙可用，切换到蓝牙
                if (bluetoothRouter != null && bluetoothRouter.isBluetoothAudioAvailable()) {
                    bluetoothRouter.switchToBluetooth();
                }

                mp.seekTo(startTime);
                mp.start();

                startTimer(duration);

                SensorUtil.initSpeaker();

                SensorUtil.initSensor(context);
//                Log.d("MediaPlayer", "总时长：" +  (double)mp.getDuration() / 1000);

                Map<String, Object> data = new HashMap<>();
                data.put("time", (double) mp.getDuration() / 1000);
                data.put("isSpeaker", !SensorUtil.getNear());

                result.success(data);
            });

            mediaPlayer.prepareAsync(); // 改为异步准备

            //初始化传感器
//            SensorUtil.initSensor(context);

        } catch (IOException e) {
            Log.e("MediaPlayer", "初始化失败: " + e.getMessage());
            result.success(-1.0);
        }
    }

    private static void initBluetoothRouter(Context context) {
        if (bluetoothRouter == null) {
            bluetoothRouter = new BluetoothAudioRouter(context, new BluetoothAudioRouter.BluetoothAudioListener() {
                @Override
                public void onBluetoothConnected() {
                    Log.d("BluetoothAudio", "蓝牙已连接，切换到蓝牙模式");
                    bluetoothRouter.switchToBluetooth();
                }

                @Override
                public void onBluetoothDisconnected() {
                    Log.d("BluetoothAudio", "蓝牙已断开，切换到正常模式");
                    boolean useSpeaker = !SensorUtil.getNear();
                    bluetoothRouter.switchToNormalMode(useSpeaker);
                }
            });

            // 注册蓝牙监听
            bluetoothRouter.registerBluetoothListener();
        }
    }

    public static boolean isBluetooth(){
        return bluetoothRouter != null && bluetoothRouter.isBluetoothAudioAvailable();
    }

    public static void pauseSpeech(Result result){
        if(mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();

                stopTimer();

                //注销传感器
                SensorUtil.unRegisterListener();

                // 切换到正常模式（保留当前扬声器状态）
                if (bluetoothRouter != null) {
                    boolean useSpeaker = !SensorUtil.getNear();
                    bluetoothRouter.switchToNormalMode(useSpeaker);
                }

                int currentPosition = mediaPlayer.getCurrentPosition();  // 获取当前播放位置（毫秒）
                double currentSeconds = currentPosition / 1000.0;
                result.success(currentSeconds);
            }
        }

    }

    public static void cancelPause(){
        if(mediaPlayer != null) {
            if (!mediaPlayer.isPlaying()) {

                // 重新激活蓝牙（如果可用）
                if (bluetoothRouter != null && bluetoothRouter.isBluetoothAudioAvailable()) {
                    bluetoothRouter.switchToBluetooth();
                }

                mediaPlayer.start();

                startTimer(_duration);

                SensorUtil.initSensor(ContextHelper.getInstance().getContext());
            }
        }

    }

    // 强化版重启方法
    public static void restartSpeech() {
        if (mediaPlayer != null) {
            try {
                // 状态检查：避免在未初始化时操作
                if (isPrepared) {
                    mediaPlayer.seekTo(0);  // 关键：回到起点
                    mediaPlayer.start();    // 直接启动（无需重复 prepare）
                } else {
                    // 异步准备未完成时强制重置
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(savedFilePath);
                    mediaPlayer.prepareAsync();
                }
            } catch (IOException e) {
                Log.e("SpeechPlayer", "重启异常: ", e);
            }
        } else {
//            startSpeech(ContextHelper.getInstance().getContext(), savedFilePath);
        }
    }


    public static void playSeekTo(int playSeekTo) {
        if (mediaPlayer != null && isPrepared) {

            // 重新激活蓝牙（如果可用）
            if (bluetoothRouter != null && bluetoothRouter.isBluetoothAudioAvailable()) {
                bluetoothRouter.switchToBluetooth();
            }

            mediaPlayer.seekTo(playSeekTo);  // 关键：回到起点
            mediaPlayer.start();    // 直接启动（无需重复 prepare）

            startTimer(_duration);
        }
    }

    public static void stopSpeech(){
        try {
            if(mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                }
                mediaPlayer.release();
                mediaPlayer = null;

                stopTimer();
            }
        } catch (Exception e) {
            Log.i("SpeechPlayer", e.toString());
        } finally {

            isPrepared = false;
            //注销传感器
            SensorUtil.unRegisterListener();

            // 释放蓝牙路由器资源
            releaseBluetoothRouter();
        }

    }

    private static void releaseBluetoothRouter() {
        if (bluetoothRouter != null) {
            // 切换到正常模式（使用扬声器）
            bluetoothRouter.switchToNormalMode(true);

            // 注销监听
            bluetoothRouter.unregisterBluetoothListener();

            // 可选：置空引用
            bluetoothRouter = null;
        }
    }

    public static MediaPlayer getMediaPlayer(){
        return mediaPlayer;
    }

    private static Handler progressHandler;
    private static Runnable updateProgressTask;

    public static void startTimer(long duration){
        if(duration <= 0){
            return;
        }
        stopTimer();

        // 初始化定时器
        if(progressHandler == null){
            progressHandler = new Handler(Looper.getMainLooper());
        }

        updateProgressTask = new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    // 获取当前播放位置（单位：毫秒）
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    SpeechPlayHelper.getInstance().onListenerPlayTime(currentPosition/1000.0);
                }
                // 每秒触发一次（1000ms）
                progressHandler.postDelayed(this, duration);
            }
        };

        progressHandler.postDelayed(updateProgressTask, duration);
    }

    public static void stopTimer(){
        if(updateProgressTask != null){
            progressHandler.removeCallbacks(updateProgressTask);
            updateProgressTask = null;
        }

    }

}
